const express = require("express");
const { login } = require("./modules/login");
const { logins } = require("./modules/logins");
const { register } = require("./modules/register");
const Cart = require("./modules/Cart");
const myself = require("./modules/myself");
const session = require("express-session")
const multer = require("multer");
const _upload = require("./modules/upload");
const setUser = require("./modules/setUser");
const { repassword } = require("./modules/repassword");
const { reheaderimg } = require("./modules/reheaderimg");
const { reheaderimgs } = require("./modules/reheaderimgs");
const { reheaderimgse } = require("./modules/reheaderimgse");
const { reheaderimgg } = require("./modules/reheaderimgg");

const fs = require("fs")
const app = express();
const upload = multer({ dest: "./upload" });
app.use(upload.any());
app.use(express.static("./www"));
app.use(express.static("./upload"));
app.use(express.urlencoded({ extended: false }));

app.use(session({
    secret: '千锋H5',   // 加密信息，可以随便写
    resave: false,     // 强制保存session，默认为true，建议设置为false
    saveUninitialized: true,   // 强制将未初始化的session存储，默认为true，建议为true
    cookie: { maxAge: 1000 * 100 }    // 过期时间，毫秒数
}));

app.get("/login", login());

app.get("/logins", logins());
app.get("/serach");

app.post("/register", register("hello"));

app.get("/Cart", Cart());

app.get("/myself", myself());

app.get("/index");


app.get("/data", (req, res, next) => {
    fs.readFile("./modules/data.json", "utf-8", (err, data) => {
        if (err) {
            res.send(JSON.stringify({
                code: 0,
                msg: "数据请求失败",
                data: null
            }))
        } else {
            res.send(JSON.stringify({
                code: 1,
                msg: "数据请求成功",
                data: JSON.parse(data)
            }))
        }
    })
})


app.get("/repassword", repassword());

app.get("/reheaderimg", reheaderimg());

app.get("/reheaderimgs", reheaderimgs());

app.get("/reheaderimgse", reheaderimgse());

app.get("/reheaderimgg", reheaderimgg());

app.post("/upload", _upload());

app.post("/setUser", setUser());

app.get("/soye", (req,res,next)=>{
    let id = req.query.pid;
    
   var s= id.split("=")[1]

//    console.log(id)
    fs.readFile("./modules/data.json", "utf-8", (err,data)=>{
        const d = JSON.parse(data);
        let i;
        const flag = d.some((val,idx)=>{
            i = idx;
            return val.pid.toString() === id;
        })

        if(flag){
            res.send(JSON.stringify({
                code:1,
                msg:"获取成功",
                data:d[i]
            }));
        }else{
            res.send(JSON.stringify({
                code:0,
                msg:"没有对应商品，请检查pid是否正确",
                data:null
            }));
        }
    })
})
app.listen(3000, () => {
    console.log("服务器开启成功,地址为: http://localhost:3000")
})
